<?php

namespace App\Http\Controllers\Api;

use App\Models\AppVersion;
use App\Models\DownloadLog;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class DownloadController extends Controller
{
    /*
     * 下载app
     * @param Request $request
     * @return bool\string
     */
    public function downloadApk(Request $request){

        if (is_wechat_browser()) {
            echo('<div style="font-size: 50px; text-align: center;line-height: 200px;">请点击右上角选择"在浏览器打开"</div>');
            exit();
        }
        $apk = AppVersion::where('push_state',1) -> orderBy('id','desc') -> first();
	
        if($apk){

            $download_url = config('app.img_url') . $apk -> download_url;
            //判断下载次数
            $downloadLog = DownloadLog::store($apk -> id, $download_url);
            if($downloadLog['error']){
                return jsonError($downloadLog['error']);
            }

            if($downloadLog){

                Header("HTTP/1.1 303 See Other");
                Header("Location: $download_url");
                //return response() -> download(realpath(base_path('public')).'\\uploads\\'. $apk -> download_url);
            }else{

                return jsonError();
            }
        }else{
            return jsonError(4031);
        }

    }


    // app最新版本
    public function getAppNewVersion()
    {

        $appVersion = AppVersion::where('push_state',1) -> orderBy('id','desc') -> get(['id','version_num','version_remark','download_url']) -> first();
        if($appVersion){
            $appVersion -> download_url = config('app.img_url') . $appVersion -> download_url;
        }

        return jsonSuccess($appVersion);
    }
}
